<template>
  <div class="music-page">
    <el-card shadow="hover" class="music-card">
      <div class="card-header">
        <h2 class="title">🎵 我的音乐播放中心</h2>
        <el-button type="primary" @click="goBack">返回</el-button>
      </div>

      <!-- 上传与输入 -->
      <div class="upload-section">
        <el-upload
          :before-upload="beforeUpload"
          :auto-upload="false"
          :file-list="fileList"
          :on-change="handleChange"
        >
          <el-button type="primary">选择 MP3 文件</el-button>
        </el-upload>

        <el-input
          v-model="title"
          placeholder="请输入歌曲名称"
          class="input-field"
        />
        <el-input
          v-model="description"
          placeholder="请输入描述"
          class="input-field"
        />

        <el-button
          type="success"
          :disabled="!selectedFile || !title"
          @click="uploadMp3"
        >
          上传 MP3
        </el-button>
      </div>

      <!-- 音乐列表 -->
      <div class="table-wrapper">
        <el-table :data="musicList" border stripe>
          <el-table-column prop="title" label="歌曲名称" width="200" />
          <el-table-column prop="artist" label="歌手" width="150" />
          <el-table-column label="播放" width="150">
            <template #default="scope">
              <el-button
                type="primary"
                size="small"
                @click="playMusic(scope.row)"
              >
                播放
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>

    <!-- 播放器 -->
    <div v-if="currentMusic" class="player-section">
      <h3 class="now-playing">🎶 当前播放：{{ currentMusic.title }}</h3>

      <!-- MP3 -->
      <audio
        v-if="currentMusic.resolvedUrl.endsWith('.mp3')"
        :src="currentMusic.resolvedUrl"
        controls
        autoplay
        class="media-player"
      ></audio>

      <!-- MP4 -->
      <video
        v-else-if="currentMusic.resolvedUrl.endsWith('.mp4')"
        :src="currentMusic.resolvedUrl"
        controls
        autoplay
        class="media-player"
      ></video>
    </div>
  </div>
</template>

<script setup>
import { ref } from "vue";
import { useRouter } from "vue-router";
import { uploadAudio } from "../api/music";

const router = useRouter();
const goBack = () => {
  router.back();
};

// 本地 public 目录音乐：直接写文件名，程序自动补上 /music/
const musicList = ref([
  {
    title: "还是会长大",
    artist: "程jiajia",
    url: "1.mp3", // 本地 public/music/xs.mp3
  },
  {
    title: "山楂树之恋",
    artist: "程jiajia",
    url: "2.mp3", // 网络路径
  },
  {
    title: "踏山河",
    artist: "七叔",
    url: "3.mp3", // 本地 public/music/xs.mp3
  },
  {
    title: "小情歌",
    artist: "苏打绿",
    url: "4.mp3", // 本地 public/music/xs.mp3
  },
  {
    title: "黄昏",
    artist: "小阿七",
    url: "5.mp3", // 本地 public/music/xs.mp3
  },
  {
    title: "天龙八部之宿敌",
    artist: "许嵩",
    url: "6.mp3", // 本地 public/music/xs.mp3
  },
  {
    title: "天份",
    artist: "薛之谦",
    url: "7.mp3", // 本地 public/music/xs.mp3
  },
  {
    title: "莫等",
    artist: "要不要吃饭",
    url: "8.mp3", // 本地 public/music/xs.mp3
  },
  {
    title: "群星",
    artist: "青花瓷",
    url: "9.mp3", // 本地 public/music/xs.mp3
  },
  {
    title: "他不懂",
    artist: "张杰",
    url: "10.mp3", // 本地 public/music/xs.mp3
  },
  {
    title: "嚣张",
    artist: "en",
    url: "11.mp3", // 本地 public/music/xs.mp3
  },
]);

const currentMusic = ref(null);

const resolveMusicUrl = (url) => {
  // 如果是完整 http(s) 地址，直接返回
  if (url.startsWith("http://") || url.startsWith("https://")) {
    return url;
  }
  // 否则认为是 public/music 下的本地文件
  return `/music/${url}`;
};

const playMusic = (music) => {
  currentMusic.value = {
    ...music,
    resolvedUrl: resolveMusicUrl(music.url),
  };
};

// 上传相关
const selectedFile = ref(null);
const fileList = ref([]);
const title = ref("");
const description = ref("");

const beforeUpload = (file) => {
  const isMp3 = file.type === "audio/mpeg";
  if (!isMp3) {
    alert("请上传 MP3 格式的音频文件！");
  }
  return isMp3;
};

const handleChange = (file, fileListParam) => {
  selectedFile.value = file.raw;
  fileList.value = fileListParam;
};

const uploadMp3 = async () => {
  if (!selectedFile.value || !title.value) {
    alert("请填写标题并选择 MP3 文件");
    return;
  }

  const formData = new FormData();
  formData.append("title", title.value);
  formData.append("fileName", selectedFile.value.name);
  formData.append("description", description.value || "");
  formData.append("fileSize", selectedFile.value.size);
  formData.append("coverUrl", "");
  formData.append("file", selectedFile.value);

  try {
    const res = await uploadAudio(formData);
    alert("上传成功，媒体ID：" + res.data);
  } catch (err) {
    alert("上传失败：" + (err.response?.data || err.message));
  }
};
</script>


<style scoped>
.music-page {
  padding: 20px;
  background: #f4f6f9;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.music-card {
  max-width: 900px;
  width: 100%;
}

.title {
  font-size: 1.4rem;
  font-weight: bold;
  margin-bottom: 16px;
}

.upload-section {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  margin-bottom: 20px;
  align-items: center;
}

.input-field {
  flex: 1;
  min-width: 200px;
}

.table-wrapper {
  overflow-x: auto;
}

.player-section {
  margin-top: 20px;
  text-align: center;
}

.now-playing {
  font-size: 1.1rem;
  color: #409eff;
  margin-bottom: 10px;
}

.player-container {
  width: 100%;
  max-width: 600px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

/* 小屏幕优化 */
@media (max-width: 768px) {
  .upload-section {
    flex-direction: column;
    align-items: stretch;
  }
}

.player-section {
  margin-top: 20px;
  text-align: center;
  width: 100%;
}

.media-player {
  width: 100%; /* 占满父容器宽度 */
  max-width: 1000px; /* 最大宽度，可根据页面调整 */
}

@media (max-width: 768px) {
  .media-player {
    max-width: 100%; /* 小屏幕时占满全宽 */
  }
}
</style>
